package com.dhcc.DRGsHosp.pdfRender.pdf;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi2.poifs.filesystem.DirectoryEntry;
import org.apache.poi2.poifs.filesystem.DocumentEntry;
import org.apache.poi2.poifs.filesystem.POIFSFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dhcc.DRGsHosp.pdfRender.freemaker.HtmlGenerator;
import com.dhcc.DRGsHosp.pdfRender.pdf.exception.DocumentGeneratingException;

public class DocDoucumentGenerator {
	private final static Logger logger = LoggerFactory.getLogger(PdfDocumentGenerator.class);

	private final static HtmlGenerator htmlGenerator;
	static {
		htmlGenerator = new HtmlGenerator();
	}
	
	/**
	 * 使用模板,模板数据,生成pdf
	 * 
	 * @Title: generate
	 * @Description: 使用模板,模板数据,生成pdf
	 * @param template
	 *            classpath中路径模板路径
	 * @param documentVo
	 *            模板数据
	 * @param outputFile
	 *            生成pdf的路径
	 * @author lihengjun 修改时间： 2013年11月5日 下午1:38:53 修改内容：新建
	 * @throws DocumentGeneratingException
	 */
	public boolean generateDoc(String template, DocumentVo documentVo,
			String outputFile) throws DocumentGeneratingException {
		Map<String, Object> variables = new HashMap<String, Object>();

		try {
			variables = documentVo.fillDataMap();
			String htmlContent = this.htmlGenerator.generate(template,
					variables);
			this.generate(htmlContent, outputFile);

			logger.info("The document [primarykey="
					+ documentVo.findPrimaryKey()
					+ "] is generated successfully,and stored in ["
					+ outputFile + "]");
		} catch (Exception e) {
			String error = "The document [primarykey="
					+ documentVo.findPrimaryKey() + "] is failed to generate";
			logger.error(error);
			throw new DocumentGeneratingException(error, e);
		}

		return true;
	}
	
	public void generate(String htmlContent, String outputFile)throws Exception {
          ByteArrayInputStream bais = null;
          FileOutputStream fos = null;
          try {
               String content = htmlContent;
//               String content = readFile("C:/Users/DHC_DAISY/Desktop/pdfRender/DRGsreport/DRGsreport.html");
               byte b[] = content.getBytes();
               bais = new ByteArrayInputStream(b);
               POIFSFileSystem poifs = new POIFSFileSystem();
               DirectoryEntry directory = poifs.getRoot();
               DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
               fos = new FileOutputStream(outputFile);
               poifs.writeFilesystem(fos);
               bais.close();
               fos.close();

          } catch (IOException e) {
                 e.printStackTrace();
          } finally {
                 if(fos != null) fos.close();
                 if(bais != null) bais.close();
          }
		
		
	}
	
	
	 /**
     * 读取html文件到字符串
     * @param filename
     * @return
     * @throws Exception
     */
    public String readFile(String filename) throws Exception {
           StringBuffer buffer = new StringBuffer("");
           BufferedReader br = null;
           try {
                  br = new BufferedReader(new FileReader(filename));
                  buffer = new StringBuffer();
                  while (br.ready())
                         buffer.append((char) br.read());
           } catch (Exception e) {
                  e.printStackTrace();
           } finally {
                  if(br!=null) br.close();
           }
           return buffer.toString();
    }
	
    public static void main(String[] args) throws Exception {
        new DocDoucumentGenerator().generate("","d:/123.doc");
 }
}
